<template>
  <div id="container"></div>
  <div class="search" v-if="showSearch">
    <div class="search-box">
      <img src="../public/logo.png" alt="" />
      <div class="input-box">
        <input
          type="text"
          name=""
          id="searchipt"
          placeholder="搜索位置、公交站、地铁站"
          @focus="handleInputFocus"
          @input="handleInput"
          @blur="handleInputBlur"
          v-model="searchQuery"
          @keyup.enter="searchAndZoom"
        />
        <div class="search-btn" @click="searchAndZoom">
          <i class="iconfont icon-search"></i>
        </div>
      </div>
      <div class="direction">
        <img
          :src="showCloseIcon ? '../public/关闭.png' : '../public/dire.png'"
          alt=""
         @click="handleDirectionClick"
        />
      </div>
    </div>
  </div>

  <div class="city">
    <span style="font-weight: 700">{{ cityname.slice(0, -1) }}</span>
    <i class="iconfont icon-iconcaretdown"></i>
  </div>

  <div
    class="weather"
    :class="{ 'slide-in': isweather, 'slide-out': !isweather }"
  >
    <div class="weather-title">{{ weathers }}<br />{{ temp }}</div>
  </div>

  <div class="loginbox">
    <img src="../public/login.jpg" alt="" />
  </div>
  <div class="controlbar">
    <div class="item" @click="handelstate" :class="{ active: isstate }">
      <span class="icon">
        <i class="iconfont icon-satellite"></i>
      </span>
      <span>卫星</span>
    </div>
    <div class="item" @click="handeltraffic" :class="{ active: istraffic }">
      <span class="icon">
        <i class="iconfont icon-icontraffic"></i>
      </span>
      <span>路况</span>
    </div>
    <div class="item" @click="handleRanging" :class="{ active: isranging }">
      <span class="icon">
        <i class="iconfont icon-icon_ranging"></i>
      </span>

      <span>测距</span>
    </div>
    <div class="item" @click="handleFullScreen">
      <span class="icon">
        <i class="iconfont icon-icon-fullscreen"></i>
      </span>

      <span>全屏</span>
    </div>
  </div>
  <div class="location" @click="handelLocation">
    <i class="iconfont icon-location"></i>
  </div>
  <div
    class="exit-fullscreen"
    @click="handleFullScreen"
    :class="{ show: isWindowFull }"
  >
    <span>退出全屏</span>
  </div>
  <div
    class="roadnet"
    :class="{ 'slide-in': isRoadNetSlide, 'slide-out': !isRoadNetSlide }"
  >
    <label for="roadnet" @click="handleRoadNet">
      <input type="checkbox" id="roadnet" v-model="isRoadNet" /><span
        >路网</span
      >
    </label>
  </div>
  <div
    class="traffic"
    :class="{ 'slide-down': istraffic, 'slide-up': !istraffic }"
  >
    <div class="top">
      <el-radio-group v-model="radio3" size="small">
        <el-radio-button label="实时" value="now" />
        <el-radio-button label="预测" value="forecast" />
      </el-radio-group>
      <div class="colors" style="font-size: 14px; color: #565656">
        <div class="title">畅通</div>
        <div class="color1"></div>
        <div class="color2"></div>
        <div class="color3"></div>
        <div class="color4"></div>
        <div class="title">拥堵</div>
      </div>
    </div>
    <div class="bottom" style="font-size: 12px">
      <span style="color: #5f6477">更新时间:</span>&nbsp;&nbsp;&nbsp;&nbsp;<span
        style="color: #565656"
        >{{ date }}&nbsp;&nbsp;&nbsp;&nbsp; {{ time }}</span
      >
    </div>
  </div>
  <!-- 搜索结果展示 -->
  <div class="all-results" v-if="showAllResults">
    <div class="results-title">找到 {{ allResults.length }} 个结果</div>
    <div
      class="result-item"
      v-for="(item, index) in allResults"
      :key="item.tempId"
      @click="handleResultClick(item)"
      @mouseout="handleResultMouseOut(item)"
      @mouseover="handleResultMouseOver(item)"
    >
      <div class="result-number">{{ index + 1 }}</div>
      <div class="result-info">
        <div class="result-name">{{ item.name }}</div>

        <div class="result-address">{{ item.address || '地址未知' }}</div>
        <img
          src="../public/dire.png"
          alt="路线"
          class="dire-image"
          v-if="selectedResult && selectedResult.tempId === item.tempId"
          @click="handleDireImageClick(item)" 
        />
      </div>
    </div>
  </div>
  <!-- 搜索提示 -->
  <div v-if="searchSuggestions.length > 0" class="suggestions">
    <div class="title">
      <div class="icon">
        <img src="../public/search.png" alt="" />
      </div>
      <div class="name">{{ searchQuery }}</div>
    </div>
    <div
      class="suggestion-item"
      v-for="(item, index) in searchSuggestions"
      :key="index"
      @click="handleSuggestionClick(item)"
      style="cursor: pointer"
    >
      <div class="icon">
        <img src="../public/location (4).png" alt="" />
      </div>
      <div class="address">
        {{ item.name
        }}<span style="font-size: 12px; color: #999999; margin-left: 10px"
          >{{ item.pname }}{{ item.cityname }}{{ item.adname }}</span
        >
      </div>
    </div>
  </div>
  <div
    class="search-item"
    :class="{ 'search-enter': isSearchOpen, 'search-leave': !isSearchOpen }"
    v-else-if="searchQuery.trim() === ''"
  >
    <div class="top">
      <div class="top-item" @click="handleFoodSearch">
        <div class="image">
          <img
            src="../public/search_food.png"
            alt=""
            style="width: 46px; height: 46px"
          />
        </div>
        <div class="text" style="font-size: 14px; color: #6a788c">美食</div>
      </div>
      <div class="top-item" @click="handleHotelSearch">
        <div class="image">
          <img
            src="../public/search_hotel.png"
            alt=""
            style="width: 46px; height: 46px"
          />
        </div>
        <div class="text" style="font-size: 14px; color: #6a788c">酒店</div>
      </div>
      <div class="top-item" @click="handleViewSearch">
        <div class="image">
          <img
            src="../public/search_view.png"
            alt=""
            style="width: 46px; height: 46px"
          />
        </div>
        <div class="text" style="font-size: 14px; color: #6a788c">景点</div>
      </div>
      <div class="top-item" @click="handleHouseSearch">
        <div class="image">
          <img
            src="../public/search_house.png"
            alt=""
            style="width: 46px; height: 46px"
          />
        </div>
        <div class="text" style="font-size: 14px; color: #6a788c">小区</div>
      </div>
    </div>
    <div class="bottom" style="font-size: 13px; color: #9b9faf">
      <div class="bottom-item" v-for="item in historyList" :key="item.id">
        <div class="left" @click="handleHistoryClick(item)">
          <div class="icon">
            <img
              src="../public/历史记录.png"
              alt=""
              style="width: 20px; height: 20px"
            />
          </div>
          <div class="text">{{ item.name }}</div>
        </div>
        <div class="close" @click="handleDeleteHistory(item.id)">
          <img
            src="../public/关闭.png"
            alt=""
            style="width: 20px; height: 20px"
          />
        </div>
      </div>
    </div>
  </div>
  <!-- 路线规划区域 -->

  <div
    class="route-planner"
    v-if="showRoutePlanner || isTransitioning"
    :class="{
      'route-enter': showRoutePlanner && !isTransitioning,
      'route-leave': !showRoutePlanner && isTransitioning,
    }"
  >
    <div class="top">
      <!-- 交通方式切换图标 -->
      <div class="top-icon">
        <div
          class="car"
          @click="selectMode('car')"
          :class="{ active: mode === 'car' }"
        >
          <img src="../public/car (1).png" alt="汽车图标" />
        </div>
        <div
          class="bus"
          @click="selectMode('bus')"
          :class="{ active: mode === 'bus' }"
        >
          <img src="../public/bus.png" alt="公交图标" />
        </div>
        <div
          class="walk"
          @click="selectMode('walk')"
          :class="{ active: mode === 'walk' }"
        >
          <img src="../public/peopleWalk.png" alt="步行图标" />
        </div>
      </div>
      <!-- 输入框区域 -->
      <div class="input-box">
        <div class="input-icon switch-icon">
          <img
            src="../public/arrow_switch_ up_down.png"
            alt="切换箭头"
            @click="switchInput"
          />
        </div>
        <div class="inputs">
          <div class="input-item .start-point">
            <span class="label" style="margin-right: 13px">起</span>
            <input
              type="text"
              :placeholder="startPoint ? '' : '请输入起点'"
              v-model="startPoint"
              @input="handlerouteInput"
              @focus="handleRouteInputFocus('start')"
              @blur="handleRouteInputBlur()"
            />
            <img
              src="../public/关闭圆圈.png"
              alt=""
              style="width: 20px; height: 20px; cursor: pointer"
              @click="startPoint = ''"
              v-if="startPoint"
            />
          </div>

          <div
            class="input-item waypoint-item"
            v-if="showWaypoint"
            :key="index"
          >
            <span class="label" style="margin-right: 13px">经</span>
            <input
              type="text"
              placeholder="请输入途径点"
              v-model="waypoint"
              @input="handlerouteInput"
              @focus="handleRouteInputFocus('waypoint')"
              @blur="handleRouteInputBlur()"
            />
            <img
              src="../public/关闭圆圈.png"
              alt=""
              style="
                width: 20px;
                height: 20px;
                cursor: pointer;
                position: absolute;
                left: 237px;
                top: 10px;
              "
              @click="waypoint = ''"
              v-if="waypoint"
            />
            <img
              src="../public/减号.png"
              alt="删除"
              class="remove-waypoint"
              @click="removeWaypoint()"
            />
          </div>
          <div class="input-item end-point">
            <span class="label">终</span>
            <input
              type="text"
              placeholder="请输入终点"
              v-model="endPoint"
              @input="handlerouteInput"
              @focus="handleRouteInputFocus('end')"
              @blur="handleRouteInputBlur()"
            />
            <img
              src="../public/关闭圆圈.png"
              alt=""
              style="
                width: 20px;
                height: 20px;
                cursor: pointer;
                position: absolute;
                right: 13px;
                top: 10px;
              "
              @click="endPoint = ''"
              v-if="endPoint"
            />
            <img
              src="../public/加号.png"
              alt=""
              class="icon2"
              @click="addWaypoint"
            />
          </div>
        </div>
      </div>
      <!-- 搜索按钮 -->
      <button class="search-btn" @click="handleRouteSearch">开车去</button>
      <!-- 关闭按钮 -->
      <div class="close" @click="handleBackToSearch">
        <img src="../public/叉.png" alt="关闭图标" />
      </div>
      <!-- 清除路线按钮 -->
      <button class="clear-btn"  @click="handleClearRoute" v-if="showClearBtn">清除路线</button>
    </div>
  </div>
  <!-- 路线规划搜索提示 -->
  <div
    v-if="routesearchSuggestions.length > 0"
    class="routesuggestions"
    :style="{ top: showWaypoint ? '280px' : '260' }"
  >
    <div class="title">
      <div class="icon">
        <img src="../public/search.png" alt="" />
      </div>
      <div class="name">{{ routesearchQuery }}</div>
    </div>
    <div
      class="routesuggestions-item"
      v-for="(item, index) in routesearchSuggestions"
      :key="index"
      style="cursor: pointer"
      @click="handleRouteSuggestionClick(item)"
    >
      <div class="icon">
        <img src="../public/location (4).png" alt="" />
      </div>
      <div class="address">
        {{ item.name
        }}<span style="font-size: 12px; color: #999999; margin-left: 10px">{{
          item.district
        }}</span>
      </div>
    </div>
  </div>
  <div class="my-location" v-if="showMyLocation" @click="handleMyLocationClick">
    <img src="../public/位置.png" alt="" style="width: 18px; height: 18px" />
    <div class="text">我的位置</div>
  </div>
  <div
    class="my-location1"
    v-if="showMyLocation1"
    @click="handleMyLocationClick"
  >
    <img src="../public/位置.png" alt="" style="width: 18px; height: 18px" />
    <div class="text">我的位置</div>
  </div>
  <!-- 路线规划结果展示 -->
  <div id="panel"></div>
  <!-- 历史记录 -->
  <div class="routehistory" v-if="showRouteHistory" :style="{ top: showWaypoint ? '280px' : '236px' }">
    <div class="title">
      <div class="icon">
        <img
          src="../public/历史记录.png"
          alt=""
          style="width: 20px; height: 20px"
        />
      </div>
      <div class="text" style="color: #414141; font-size: 14px; font-weight: 400; ">
        路线搜索记录
      </div>
    </div>
    <div class="history-list">
      <div class="list-item" v-for="item in routehistoryList" :key="item.id">
              <div class="left" @click="handleRouteHistoryClick(item)">
        <div class="icon">
        <img
          src="../public/search.png"
          alt=""
          style="width: 18px; height: 18px"
          class="search-icon"
        />
      </div>
      <div class="text" style="font-size: 12px; color: #666867">{{ item.points.start_point }}</div>
        <div class="jiantou" v-if="item.points.pass_point!== ''">
        <img src="../public/箭头_向右_o.png" alt="" style="width: 20px; height: 20px" />
      </div>
      <div class="text waypoint" v-if="item.points.pass_points !== ''" style="font-size: 12px; color: #666867; margin-left: 5px;">
        {{ item.points.pass_point }}
      </div>
       <div class="jiantou">
        <img src="../public/箭头_向右_o.png" alt="" style="width: 20px; height: 20px" />
      </div>
      <div class="text" style="font-size: 12px; color: #666867">{{ item.points.end_point }}</div>
    </div>
    <div class="close" @click="handleDeleteRouteHistory(item.id)">
      <img src="../public/关闭.png" alt="" style="width: 20px; height: 20px">
    </div>
      </div>  
    
      </div>

  </div>

</template>
<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import {
  getHistoryApi,
  addHistoryApi,
  deleteHistoryApi,
} from '@/assets/api/history';
import {
  getrouteHistoryApi,
  addrouteHistoryApi,
  deleterouteHistoryApi,
} from '@/assets/api/route';
import AMapLoader from '@amap/amap-jsapi-loader';
const routesearchSuggestions = ref([]);
const routesearchQuery = ref('');
const isshowWaypoints = ref(false);
const showMyLocation1 = ref(false);
const historyList = ref([]);
const routehistoryList = ref([]);
let map = null;
const center = ref();
let locationMarker = null;
const isWindowFull = ref(false);
const isranging = ref(false);
let mouseTool = null;
let Satellitelayer = null;
let RoadNetlayer = null;
const isstate = ref(false);
const isRoadNet = ref(false);
const isRoadNetSlide = ref(false);
let trafficLayer = null;
const istraffic = ref(false);
const radio3 = ref('now');
const isweather = ref(true);
const cityname = ref('合肥');
const weathers = ref('小雨');
const temp = ref('24/29℃');
const isSearchOpen = ref(false);
// 搜索提示相关变量
const searchQuery = ref(''); // 绑定输入框的值
const searchSuggestions = ref([]); // 存储搜索提示项
// 批量结果相关变量
const allResults = ref([]); // 存储所有搜索结果
const showAllResults = ref(false); // 控制结果区域显示/隐藏
const showSearchResult = ref(false);
// 新增变量：跟踪选中的结果
const selectedResult = ref(null);
const searchMarkers = ref([]);
const showCloseIcon = ref(false);
// 控制搜索框和路线规划器的显示状态
const showSearch = ref(true);
const showRoutePlanner = ref(false);
const isTransitioning = ref(false);
// 路线规划相关变量
const startPoint = ref('');
const endPoint = ref('');

const mode = ref('car'); // 默认交通方式为驾车
// 用于判断是否有途径点，控制高度变化
const hasWaypoint = ref(false);
const showMyLocation = ref(false);
// 我所在的位置
const myLocation = ref('');
const points = ref([]);
const startaddress = ref('');
const endaddress = ref('');
const waypointaddress = ref('');
// 修改原有的途径点相关变量
const showWaypoint = ref(false); // 控制是否显示途径点输入框
const waypoint = ref(''); // 单个途径点的值
const showRouteHistory = ref(false);
const currentRoute = ref(null); // 统一保存当前路线规划实例，替代原currentDriving
const transitOptions = ref({
  city: '',          // 公交城市
  policy: AMap.TransferPolicy.LEAST_TIME // 公交策略：最快路线
});

window._AMapSecurityConfig = {
  securityJsCode: '08165e04a75d24f997da481e8b2a22bb',
};
onMounted(async () => {
  const AMap = await AMapLoader.load({
    key: 'c315dd639ff69552de2837d287b2c6e2', //申请好的 Web 端开发者 Key，首次调用 load 时必填

    version: '2.0', //指定要加载的 JS API 的版本，缺省时默认为 1.4.15,
    plugins: [
      'AMap.ToolBar',
      'AMap.Scale',
      'AMap.MapType',
      'AMap.Geolocation',
      'AMap.ControlBar',
      'AMap.Marker',
      'AMap.MouseTool',
      'AMap.CitySearch',
      'AMap.Geocoder',
      'AMap.Weather',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Driving',
      'AMap.DragRoute',
      'AMap.Walking',
      'AMap.Transfer',
    ], //需要使用的插件列表，如比例尺'AMap.Scale'
  });

  map = new AMap.Map('container', {
    viewMode: '3D', //使用3D视图
    zoom: 17, //初始化地图层级
  });
  // 加载卫星地图
  Satellitelayer = new AMap.TileLayer.Satellite();
  // 加载路网地图
  RoadNetlayer = new AMap.TileLayer.RoadNet();
  // 加载路况图层
  trafficLayer = new AMap.TileLayer.Traffic();

  //添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
  map.addControl(
    new AMap.ToolBar({
      position: {
        bottom: '10px',
        right: '40px',
      }, //位置
    })
  );
  //添加比例尺控件，展示地图在当前层级和纬度下的比例尺
  map.addControl(new AMap.Scale());

  //添加控制罗盘控件，用来控制地图的旋转和倾斜
  map.addControl(
    new AMap.ControlBar({
      position: {
        right: '10px',
        bottom: '130px',
      }, //位置
    })
  );

  // 浏览器定位
  AMap.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation({});

    geolocation.getCurrentPosition(function (status, result) {
      if (status == 'complete') {
        onComplete(result);
      } else {
        onError(result);
      }
    });

    function onComplete(data) {
      map.setCenter(data.position);

      center.value = data.position;

      addLocationMarker(center.value);
    
      const geocoder = new AMap.Geocoder({});
      
      geocoder.getAddress(center.value, function (status, result) {
        if (status === 'complete' && result.regeocode) {
          console.log(result)
          // 更新我的位置
        myLocation.value = result.regeocode.formattedAddress;
        }
      })
      geocoder.getAddress(map.getCenter(), function (status, result) {
        if (status === 'complete' && result.regeocode) {
          cityname.value = result.regeocode.addressComponent.city || '';
        }
      });
    }

    function onError(data) {
      console.log(data);
    }
  });

  // 绘制/更新定位标记
  function addLocationMarker(position) {
    // 如果已有标记，先移除旧标记
    if (locationMarker) {
      map.remove(locationMarker);
    }

    // // 创建新标记（自定义图标）
    locationMarker = new AMap.Marker({
      position: position, // 标记位置（经纬度数组）
      icon: new AMap.Icon({
        size: new AMap.Size(24, 24), // 图标尺寸
        image: '../public/位置.png', // 图标路径（替换为你的图标）
        imageSize: new AMap.Size(24, 24), // 图标显示尺寸
      }),
      anchor: 'bottom-center', // 图标锚点（底部中心点与定位点对齐）
      zIndex: 100, // 确保标记显示在地图图层上方
      draggable: true, // 标记可拖拽
    });

    // 将标记添加到地图
    map.add(locationMarker);
  }
  const geocoder = new AMap.Geocoder({});

  map.on('moveend', function () {
    const zoom = map.getZoom(); // 获取当前缩放级别
    geocoder.getAddress(map.getCenter(), function (status, result) {
      if (status === 'complete' && result.regeocode) {
        
        
        if (zoom <= 10) {
          // 缩放级别低：显示省份
          cityname.value = result.regeocode.addressComponent.province || '';
        } else {
          // 缩放级别高：显示城市
          cityname.value = result.regeocode.addressComponent.city || '';

          const weather = new AMap.Weather();
          weather.getLive(cityname.value, function (status, data) {
            // 先判断接口是否调用成功
            if (status === 'complete' && data) {
              weathers.value = data.weather || '未知';
              temp.value = (data.temperature || '未知') + '℃';
            } else {
              // 接口调用失败时的处理
              weathers.value = data.weather;
              temp.value = data.temperature + '℃';
            }
          });
        }
      }
    });
  });

  // 缩放事件只处理天气显示状态，不绑定moveend
  map.on('zoomend', function () {
    const zoom = map.getZoom();
    isweather.value = zoom > 10; // 缩放>10级显示天气，否则隐藏
    // 缩放后主动触发一次moveend，更新城市名（可选，优化体验）
    map.emit('moveend');
  });

  // 初始化时触发一次moveend，获取初始城市名
  map.emit('moveend');

  // 获取历史记录
  historyList.value = await getHistoryApi();
  routehistoryList.value = await getrouteHistoryApi();
});

const handleRanging = () => {
  if (isranging.value) {
    mouseTool.close();
    isranging.value = false;
  } else {
    mouseTool = new AMap.MouseTool(map);
    //在插件的回调函数中使用功能
    mouseTool.rule({
      startMarkerOptions: {
        //设置量测起始点标记属性对象 可缺省
        icon: new AMap.Icon({
          size: new AMap.Size(19, 31), //图标大小
          imageSize: new AMap.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/start.png',
        }),
        offset: new AMap.Pixel(-9, -31),
      },
      endMarkerOptions: {
        //设置量测结束点标记属性对象 可缺省
        icon: new AMap.Icon({
          size: new AMap.Size(19, 31), //图标大小
          imageSize: new AMap.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/end.png',
        }),
        offset: new AMap.Pixel(-9, -31),
      },
      midMarkerOptions: {
        //设置拖拽路线插件途经点点标记属性对象 可缺省
        icon: new AMap.Icon({
          size: new AMap.Size(19, 31), //图标大小
          imageSize: new AMap.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/mid.png',
        }),
        offset: new AMap.Pixel(-9, -31),
      },
      lineOptions: {
        //可缺省
        strokeStyle: 'solid',
        strokeColor: '#FF33FF',
        strokeOpacity: 1,
        strokeWeight: 2,
      },
    });
    isranging.value = true;
  }
};

function handelLocation() {
  map.setCenter(center.value);
 
  // 可选：添加定位动画，增强用户体验
  map.setZoom(15, true); // 第二个参数为true时开启动画
}

// 处理全屏切换
const handleFullScreen = () => {
  const container = document.getElementById('container');
  const otherElements = document.querySelectorAll(
    '.search, .citybox, .loginbox, .controlbar, .location'
  );

  if (!isWindowFull.value) {
    // 进入全屏：显示地图并隐藏其他元素
    container.style.position = 'fixed';
    container.style.top = '0';
    container.style.left = '0';
    container.style.width = '100vw';
    container.style.height = '100vh';
    container.style.zIndex = '9999';
    otherElements.forEach((el) => (el.style.display = 'none'));

    // 只需切换状态，动画由 CSS 类控制
    isWindowFull.value = true;
  } else {
    // 退出全屏：恢复地图样式并显示其他元素
    container.style.position = '';
    container.style.top = '';
    container.style.left = '';
    container.style.width = '100%';
    container.style.height = '100vh';
    container.style.zIndex = '';
    otherElements.forEach((el) => (el.style.display = ''));

    // 切换状态，触发退出动画
    isWindowFull.value = false;
  }

  map?.resize();
};

// 切换卫星地图
const handelstate = () => {
  if (isstate.value) {
    Satellitelayer.setMap(null);
    isstate.value = false;
    isRoadNetSlide.value = false;
    RoadNetlayer.setMap(null);
    isRoadNet.value = false;
  } else {
    Satellitelayer.setMap(map);
    isstate.value = true;
    // 强制显示路网并更新复选框勾选状态
    RoadNetlayer.setMap(map);
    isRoadNet.value = true;
    isRoadNetSlide.value = true;
  }
};
// 控制路网图层显示/隐藏
const handleRoadNet = () => {
  if (!isRoadNet.value) {
    RoadNetlayer.setMap(map); // 显示路网
  } else {
    RoadNetlayer.setMap(null); // 隐藏路网
  }
};
// 路况图层显示/隐藏
const handeltraffic = () => {
  if (istraffic.value) {
    trafficLayer.setMap(null);
    istraffic.value = false;
  } else {
    trafficLayer.setMap(map);
    istraffic.value = true;
  }
};

// 输入框获得焦点时
const handleInputFocus = () => {
  // 可以在这里添加延迟，让动画更自然
  setTimeout(() => {
    isSearchOpen.value = true;
    showAllResults.value = false;
  }, 50);
};

// 输入框有内容输入时
const handleInput = () => {
  if (searchQuery.value.trim().length > 0) {
    const center = map.getCenter();
    const placeSearch = new AMap.PlaceSearch({
      map: null, // 输入时不关联地图，避免自动添加标记
      pageSize: 10,
    });
    // 仅获取搜索建议，不添加地图标记
    placeSearch.searchNearBy(
      searchQuery.value.trim(),
      center,
      10000,
      (status, result) => {
        if (status === 'complete' && result.poiList) {
          searchSuggestions.value = result.poiList.pois;
        } else {
          searchSuggestions.value = []; // 搜索失败时清空建议
        }
      }
    );
    isSearchOpen.value = true;
  } else {
    searchSuggestions.value = [];
  }
};
// 路线规划输入时
// 在现有变量中添加
const activeInput = ref(''); // 跟踪当前活跃的输入框：'start' | 'end' | `waypoint-${index}`

// 处理路线规划输入框聚焦事件

const handleRouteInputFocus = (type) => {
  activeInput.value = type;
  // 聚焦时如果已有内容，触发一次搜索

  if (
    (type === 'start' && startPoint.value) ||
    (type === 'end' && endPoint.value) ||
    (type === 'waypoint' && waypoint.value)
  ) {
    handlerouteInput();
  }
  if (showWaypoint.value == true) {
    showMyLocation1.value = true;
    showMyLocation.value = false;
  } else {
    showMyLocation.value = true;
    showMyLocation1.value = false;
  }
};
// 失去焦点事件
const handleRouteInputBlur = () => {
  // showMyLocation.value = false;
  // showMyLocation1.value = false;
  // routesearchSuggestions.value = [];
};
// 处理路线规划提示项点击
const handleRouteSuggestionClick = (item) => {
  if (activeInput.value === 'start') {
    startaddress.value = item.address;
    startPoint.value = item.name;
  } else if (activeInput.value === 'end') {
    endPoint.value = item.name;
    endaddress.value = item.address;
  } else if (activeInput.value === 'waypoint') {
    waypoint.value = item.name;
    waypointaddress.value = item.address;
  }
  routesearchSuggestions.value = []; // 清空提示
};

// 完善路线规划输入处理函数
const handlerouteInput = () => {
  showRouteHistory.value = false;
  // 隐藏路线规划结果面板
  const panel = document.getElementById('panel');
  if (panel) {
    panel.style.display = 'none';
  }

  let keyword = '';
  // 根据当前活跃输入框获取关键词
  if (activeInput.value === 'start') {
    keyword = startPoint.value.trim();
  } else if (activeInput.value === 'end') {
    keyword = endPoint.value.trim();
  } else if (activeInput.value === 'waypoint') {
    keyword = waypoint.value.trim();
  }

  // 输入内容不为空时隐藏"我的位置"提示
  if (keyword) {
    showMyLocation.value = false;
    showMyLocation1.value = false;
  }

  if (!keyword) {
    routesearchSuggestions.value = [];
    return;
  }

  routesearchQuery.value = keyword;

  // 获取当前城市作为搜索范围
  const geocoder = new AMap.Geocoder({});
  geocoder.getAddress(map.getCenter(), (status, result) => {
    const city =
      status === 'complete' && result.regeocode
        ? result.regeocode.addressComponent.city || ''
        : cityname.value;

    const autoOptions = { city };
    const autoComplete = new AMap.AutoComplete(autoOptions);

    autoComplete.search(keyword, (status, result) => {
      if (status === 'complete' && result.tips) {
        routesearchSuggestions.value = result.tips.slice(1, 10); // 取前10条建议
      } else {
        routesearchSuggestions.value = [];
      }
    });
  });
};
// 在现有ref变量中添加
const showClearBtn = ref(false); // 控制清除按钮显示状态
const currentDriving = ref(null); // 保存当前路线规划实例

// 修改handleRouteSearch方法
const handleRouteSearch = () => {
  showRouteHistory.value = false;
  
  // 清除现有路线
  if (currentRoute.value) {
    currentRoute.value.clear();
    currentRoute.value = null;
  }

  // 显示清除按钮和结果面板
  showClearBtn.value = true;
  const panel = document.getElementById('panel');
  if (panel) {
    panel.style.display = 'block';
  }

  // 构建路线点数组
  points.value = [
    {
      keyword: startPoint.value === '我的位置' ? myLocation.value : startPoint.value,
      city: cityname.value,
    }
  ];

  // 添加途径点（仅驾车支持途径点）
  if (mode.value === 'car' && showWaypoint.value && waypoint.value) {
    points.value.push({
      keyword: waypoint.value === '我的位置' ? myLocation.value : waypoint.value,
      city: cityname.value,
    });
  }

  // 添加终点
  points.value.push({
    keyword: endPoint.value === '我的位置' ? myLocation.value : endPoint.value,
    city: cityname.value,
  });

  // 根据交通方式选择不同的路线规划服务
  switch(mode.value) {
    case 'car':
      currentRoute.value = new AMap.Driving({
        map: map,
        panel: 'panel',
        policy: AMap.DrivingPolicy.LEAST_TIME // 最快路线
      });
      break;
      
    case 'bus':
      // 设置公交城市
      transitOptions.value.city = cityname.value;
      currentRoute.value = new AMap.Transfer({
        map: map,
        panel: 'panel',
        policy: transitOptions.value.policy,
        city: transitOptions.value.city
      });
      break;
      
    case 'walk':
      currentRoute.value = new AMap.Walking({
        map: map,
        panel: 'panel'
      });
      break;
  }

  // 执行路线搜索
  currentRoute.value.search(points.value, function (status, result) {
    if (status === 'complete') {
      console.log(`${mode.value}路线规划成功`, result);
      // 保存路线历史记录
      saveRouteHistory();
      // 调整地图视野
      map.setFitView();
    } else {
      console.log(`${mode.value}路线规划失败`, status);
    }
  });
};


// 实现清除路线方法
const handleClearRoute = () => {
  // 清除地图上的路线
    if (currentRoute.value) {
    currentRoute.value.clear();
    currentRoute.value = null;
  }

  // 隐藏结果面板
  const panel = document.getElementById('panel');
  if (panel) {
    panel.style.display = 'none';
  }

  // 清空输入框
  startPoint.value = '';
  endPoint.value = '';
  waypoint.value = '';
  startaddress.value = '';
  endaddress.value = '';
  waypointaddress.value = '';
  
  // 隐藏途径点输入框
  showWaypoint.value = false;
  
  // 隐藏清除按钮
  showClearBtn.value = false;
  
  // 清空路线点数组
  points.value = [];
  
  // 重置活跃输入状态
  activeInput.value = '';
};
// 新增保存路线历史的方法
const saveRouteHistory = async () => {
  // 准备要保存的路线数据
  const routeData = {
    id: Date.now(), // 使用时间戳作为唯一ID
    points: {
      start_point: startPoint.value ,
      end_point: endPoint.value ,
      pass_point: showWaypoint.value && waypoint.value 
        ? waypoint.value 
        : '' // 没有途径点时为空
    }
  };

  try {
    // 调用API保存历史记录
    await addrouteHistoryApi(routeData);
    // 重新获取历史记录列表，更新UI
    routehistoryList.value = await getrouteHistoryApi();
    console.log('路线历史记录保存成功');
  } catch (error) {
    console.error('保存路线历史失败:', error);
  }
};
// 修改 handleMyLocationClick 方法
const handleMyLocationClick = () => {
  console.log('当前位置:', myLocation.value);
  console.log('活跃输入框:', activeInput.value);

  if (!myLocation.value) {
    console.error('未获取到当前位置');
    return;
  }

  // 在输入框中显示"我的位置"文本（而非实际地址）
  if (activeInput.value === 'start') {
    startPoint.value = '我的位置';
    startaddress.value = myLocation.value; // 仍存储实际地址用于路线规划
  } else if (activeInput.value === 'end') {
    endPoint.value = '我的位置';
    endaddress.value = myLocation.value;
  } else if (activeInput.value === 'waypoint') {
    waypoint.value = '我的位置';
    waypointaddress.value = myLocation.value;
  }

  // 清空建议并隐藏提示
  routesearchSuggestions.value = [];
  showMyLocation.value = false;
  showMyLocation1.value = false;

  // 获取当前活跃的输入框DOM元素并使其失去焦点
  let inputElement = null;
  if (activeInput.value === 'start') {
    inputElement = document.querySelector('.start-point input');
  } else if (activeInput.value === 'end') {
    inputElement = document.querySelector('.end-point input');
  } else if (activeInput.value === 'waypoint') {
    inputElement = document.querySelector('.waypoint-item input');
  }

  // 触发失去焦点事件
  if (inputElement) {
    inputElement.blur();
  }

  // 重置活跃输入框状态
  activeInput.value = '';
};
// 输入框失去焦点时
const handleInputBlur = () => {
  if (searchQuery.value.trim().length > 0) {
    // ... 原有搜索建议逻辑 ...
    showAllResults.value = false; // 输入时隐藏结果区域
  } else {
    searchSuggestions.value = [];
    //  isSearchOpen.value = false;
  }
};

const searchAndZoom = async (searchType, shouldAddHistory = true) => {
  if (searchQuery.value.trim().length === 0) return;

  // 1. 清除之前的搜索标记
  searchMarkers.value.forEach((marker) => {
    map.remove(marker);
  });
  searchMarkers.value = []; // 清空标记数组
  selectedResult.value = null; // 重置选中状态

  // 2. 执行搜索并添加新标记
  const center = map.getCenter();

  const placeSearch = new AMap.PlaceSearch({
    map: null, // 手动控制标记，不自动添加
    pageSize: 20,
  });
  placeSearch.searchNearBy(
    searchQuery.value.trim(),
    center,
    10000,

    (status, result) => {
      // 隐藏原搜索建议
      searchSuggestions.value = [];
      // 隐藏单个结果区域（若之前有）
      showSearchResult.value = false;
      if (status === 'complete' && result.poiList && result.poiList.pois) {
        const results = result.poiList.pois.filter((poi) => poi.location);
        // 存储所有结果
        allResults.value = results;
        // 显示批量结果区域
        showAllResults.value = true;

        // 添加新标记并存储到数组
        results.forEach((poi, index) => {
          // 为每个标记创建唯一ID，用于查找DOM元素
          const markerId = `custom-marker-${Date.now()}-${index}`;
          poi.tempId = markerId;
          const markerContent = `
            <div id="${markerId}" style="position: relative; width: 36px; height: 40px;" class="custom-marker">
              <img
                src="../public/location-pin.png"
                alt="marker"
                style="width: 100%; height: 100%; transition: all 0.2s ease;"
                class="marker-image"
              />
              <div style="position: absolute; top: 5px; left: 50%; transform: translateX(-50%);
                          color: #fff; font-size: 12px; font-weight: bold;
                          padding: 2px 6px; border-radius: 4px;">${
                            index + 1
                          }</div>
            </div>
          `;
          const marker = new AMap.Marker({
            position: poi.location,
            title: poi.name,
            content: markerContent,
            // 确保标记锚点在底部中心
            anchor: 'bottom-center',
            tempId: markerId,
          });
          map.add(marker);
          searchMarkers.value.push(marker); // 存入数组便于后续清除

          setTimeout(() => {
            const img = document.querySelector(`#${markerId} .marker-image`);
            if (img) {
              // 先移除可能存在的动画类，确保每次都能触发动画
              img.classList.remove('animate-fall');
              // 强制重绘
              void img.offsetWidth;
              // 添加动画类
              img.classList.add('animate-fall');
            }
          }, index * 50); // 每个标记延迟递增，形成瀑布流效果
          marker.infoWindow = new AMap.InfoWindow({
            content: `<style>
             .custom-info-window {
                background-color: #fff;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                padding: 10px;
                font-size: 14px;
                color: #333;
              }
                </style>
              <div class="custom-info-window">
                <div class="custom-info-title" style="font-size: 14px;">${poi.name}</div>
              </div>
            `,
            offset: new AMap.Pixel(0, -45), // 调整信息窗口位置
            closeWhenClickMap: true, // 点击地图关闭信息窗口
            isCustom: true, // 使用自定义信息窗口，去除默认样式
          });

          // 鼠标移入显示信息窗口并更换图片

          marker.on('mouseover', () => {
            const img = document.querySelector(`#${markerId} .marker-image`);
            if (img) img.src = '../public/location-pin (1).png';

            if (window.currentInfoWindow) window.currentInfoWindow.close();
            marker.infoWindow.open(map, marker.getPosition());
            window.currentInfoWindow = marker.infoWindow;
          });

          // 鼠标移出关闭信息窗口并恢复图片

          marker.on('mouseout', () => {
            // 1. 仅在未选中状态下恢复默认图标
            if (
              !selectedResult.value ||
              selectedResult.value.tempId !== markerId
            ) {
              const img = document.querySelector(`#${markerId} .marker-image`);
              if (img) img.src = '../public/location-pin.png'; // 恢复默认图标
            }

            // 2. 正确引用 marker 自身的 infoWindow 并关闭
            if (marker.infoWindow) {
              marker.infoWindow.close();
            }
          });
        });

        let zoomLevel = 14; // 默认值
        switch (searchType) {
          case 'food':
            zoomLevel = 17;
            break;
          case 'hotel':
            zoomLevel = 16;
            break;
          case 'view':
            zoomLevel = 15;
            break;
          case 'house':
            zoomLevel = 16;
            break;
        }

        // 设置缩放级别，开启动画
        map.setZoom(zoomLevel, true);

        // 如果有搜索结果，将地图中心定位到第一个结果
        if (results.length > 0) {
          map.setCenter(results[0].location, true);
          // 自动显示第一个结果的弹窗（可选）
          const firstMarker = searchMarkers.value[0];
          if (firstMarker) {
            showInfoWindow(firstMarker);
          }
        }
      }
    }
  );

  // 4. 关闭搜索面板
  isSearchOpen.value = false;
  showCloseIcon.value = true;

  // 仅当需要添加历史时才执行以下代码
  if (shouldAddHistory) {
    // 新增判断
    // 生成唯一ID
    const historyId = Date.now() + Math.floor(Math.random() * 1000);
    const historyData = {
      id: historyId, // 保留id字段
      name: searchQuery.value.trim(), // 添加name字段，值为搜索内容
      address: searchQuery.value.trim(), // 保持address字段
    };

    // 添加到历史记录
    await addHistoryApi(historyData);
    historyList.value.unshift(historyData); // 前端列表同步更新
  }
};

const handleFoodSearch = () => {
  searchQuery.value = '美食';
  // 清空搜索建议
  searchSuggestions.value = [];
  // 关闭搜索面板
  isSearchOpen.value = false;
  // 执行搜索
  searchAndZoom('food', false);
};
// 酒店搜索
const handleHotelSearch = () => {
  searchQuery.value = '酒店';
  searchSuggestions.value = []; // 清空搜索建议
  isSearchOpen.value = false; // 关闭搜索面板
  searchAndZoom('hotel', false); // 执行搜索
};

// 景点搜索
const handleViewSearch = () => {
  searchQuery.value = '景点';
  searchSuggestions.value = [];
  isSearchOpen.value = false;
  searchAndZoom('view', false);
};

// 小区搜索
const handleHouseSearch = () => {
  searchQuery.value = '小区';
  searchSuggestions.value = [];
  isSearchOpen.value = false;
  searchAndZoom('house', false);
};
// 显示指定标记的信息窗口
const showInfoWindow = (marker) => {
  // 安全检查：确保标记和信息窗口存在
  if (!marker || !marker.infoWindow) {
    console.warn('标记或信息窗口不存在');
    return;
  }

  // 关闭当前已打开的窗口
  if (window.currentInfoWindow) {
    window.currentInfoWindow.close();
  }
  // 更新信息窗口内容，添加右侧图片
  marker.infoWindow.setContent(`
    <style>
      .custom-info-window {
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 10px;
        font-size: 14px;
        color: #333;
        display: flex;
        align-items: center;
        justify-content: space-between;

      }
      .info-content {
        flex-grow: 1;
      }
      .info-image {
        margin-left: 10px;
        width: 20px;
        height: 20px;
      }
    </style>
    <div class="custom-info-window">
      <div class="info-content">
        <div class="custom-info-title" style="font-size: 14px;">${marker.getTitle()}</div>
      </div>
      <img src="../public/dire.png" alt="路线" class="info-image" />
    </div>
  `);

  // 显示目标窗口
  marker.infoWindow.open(map, marker.getPosition());
  // 记录当前打开的窗口
  window.currentInfoWindow = marker.infoWindow;
};

// 关闭信息窗口
const closeInfoWindow = () => {
  if (window.currentInfoWindow) {
    window.currentInfoWindow.close();
    window.currentInfoWindow = null;
  }
};
// 处理结果项鼠标悬停
const handleResultMouseOver = (item) => {
  const marker = searchMarkers.value.find((marker) =>
    marker.getContent().includes(item.tempId)
  );

  if (marker) {
    // 切换图标
    const img = document.querySelector(`#${item.tempId} .marker-image`);
    if (img) img.src = '../public/location-pin (1).png';

    // 显示弹窗（已在showInfoWindow中做安全检查）
    showInfoWindow(marker);
  } else {
    console.warn('未找到对应的标记');
  }
};

// 处理结果项鼠标离开
const handleResultMouseOut = (item) => {
  // 非选中状态时恢复图标并关闭弹窗
  if (!selectedResult.value || selectedResult.value.tempId !== item.tempId) {
    const marker = searchMarkers.value.find((marker) =>
      marker.getContent().includes(item.tempId)
    );
    if (marker) {
      const img = document.querySelector(`#${item.tempId} .marker-image`);
      if (img) img.src = '../public/location-pin.png'; // 恢复默认图标
      closeInfoWindow(); // 关闭弹窗
    }
  }
};

// 公共处理函数：处理选中项（搜索提示/搜索结果共用）
const handleItemSelect = (item) => {
  // 1. 状态更新
  searchQuery.value = item.name;
  showCloseIcon.value = true;
  isSearchOpen.value = false;
  searchSuggestions.value = [];
  allResults.value = [item]; // 只显示当前选中项
  showAllResults.value = true;

  // 2. 清除旧标记
  searchMarkers.value.forEach((marker) => map.remove(marker));
  searchMarkers.value = [];
  selectedResult.value = null;

  // 3. 获取位置（搜索结果已有location，直接使用）
  const position = item.location;
  if (!position) {
    console.error('无效位置信息');
    return;
  }

  // 4. 创建唯一标记ID
  const markerId = `custom-marker-${Date.now()}`;
  item.tempId = markerId;

  // 5. 创建标记（统一使用选中状态图标）
  const markerContent = `
    <div id="${markerId}" style="position: relative; width: 36px; height: 40px;" class="custom-marker">
      <img
        src="../public/location-pin (1).png"
        alt="marker"
        style="width: 100%; height: 100%;"
        class="marker-image"
      />
      <div style="position: absolute; top: 5px; left: 50%; transform: translateX(-50%);
                  color: #fff; font-size: 12px; font-weight: bold;
                  padding: 2px 6px; border-radius: 4px;">1</div>
    </div>
  `;
  const marker = new AMap.Marker({
    position: position,
    title: item.name,
    content: markerContent,
    anchor: 'bottom-center',
    tempId: markerId,
  });
  map.add(marker);
  searchMarkers.value.push(marker);

  // 6. 创建统一样式的信息窗口
  marker.infoWindow = new AMap.InfoWindow({
    content: `
      <style>
        .custom-info-window {
          background-color: #fff;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          padding: 10px;
          font-size: 14px;
          color: #333;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .info-content { flex-grow: 1; }
        .info-image { margin-left: 10px; width: 20px; height: 20px; }
      </style>
      <div class="custom-info-window">
        <div class="info-content">
          <div class="custom-info-title">${item.name}</div>
        </div>
        <img src="../public/dire.png" alt="路线" class="info-image" />
      </div>
    `,
    offset: new AMap.Pixel(0, -45),
    closeWhenClickMap: true,
    isCustom: true,
  });


  // 7. 标记选中状态并显示信息窗口
  selectedResult.value = item;
  marker.infoWindow.open(map, position);
  window.currentInfoWindow = marker.infoWindow;

  // 8. 统一地图定位（缩放至17级，开启动画）
  map.setCenter(position, true);
  map.setZoom(17, true);

  // 9. 统一添加历史记录
  const historyId = Date.now() + Math.floor(Math.random() * 1000);
  const historyData = {
    id: historyId,
    name: item.name,
    address: item.address || item.name,
  };
  addHistoryApi(historyData);
  historyList.value.unshift(historyData);
};
// 处理搜索结果点击
const handleResultClick = (item) => {
  handleItemSelect(item);
};

// 处理搜索提示点击
const handleSuggestionClick = (item) => {
  handleItemSelect(item);
};
// 添加删除历史记录的方法
const handleDeleteHistory = async (id) => {
  try {
    // 找到要删除的历史记录的索引
    const index = historyList.value.findIndex((item) => item.id === id);
    if (index !== -1) {
      await deleteHistoryApi(id);
      // 删除成功后从列表中移除
      historyList.value.splice(index, 1);
    }
  } catch (error) {
    console.error('删除历史记录失败:', error);
  }
};

// 处理历史记录点击
const handleHistoryClick = (historyItem) => {
  // 1. 填充输入框并更新状态（与搜索提示逻辑一致）
  searchQuery.value = historyItem.name;
  showCloseIcon.value = true;
  isSearchOpen.value = false;
  searchSuggestions.value = [];

  // 2. 清除之前的搜索标记
  searchMarkers.value.forEach((marker) => {
    map.remove(marker);
  });
  searchMarkers.value = [];
  selectedResult.value = null;

  // 3. 通过历史记录的地址获取位置信息
  const getPosition = async () => {
    return new Promise((resolve) => {
      const geocoder = new AMap.Geocoder();
      // 使用历史记录的地址进行地理编码
      geocoder.getLocation(historyItem.address, (status, result) => {
        if (status === 'complete' && result.geocodes.length > 0) {
          resolve(result.geocodes[0].location);
        } else {
          // 编码失败时使用地图当前中心
          resolve(map.getCenter());
        }
      });
    });
  };

  // 4. 处理位置并执行核心逻辑（与搜索提示逻辑完全一致）
  getPosition().then((position) => {
    // 构造与搜索提示项结构一致的临时数据
    const tempItem = {
      name: historyItem.name, // 历史记录的名称
      address: historyItem.address, // 历史记录的地址
      location: position,
    };

    // 存储为单个结果并显示
    allResults.value = [tempItem];
    showAllResults.value = true;

    // 创建唯一标记ID
    const markerId = `custom-marker-${Date.now()}`;
    tempItem.tempId = markerId;

    // 创建标记
    const markerContent = `
      <div id="${markerId}" style="position: relative; width: 36px; height: 40px;" class="custom-marker">
        <img
          src="../public/location-pin (1).png"
          alt="marker"
          style="width: 100%; height: 100%;"
          class="marker-image"
        />
        <div style="position: absolute; top: 5px; left: 50%; transform: translateX(-50%);
                    color: #fff; font-size: 12px; font-weight: bold;
                    padding: 2px 6px; border-radius: 4px;">1</div>
      </div>
    `;
    const marker = new AMap.Marker({
      position: position,
      title: tempItem.name,
      content: markerContent,
      anchor: 'bottom-center',
    });
    map.add(marker);
    searchMarkers.value.push(marker);

    // 创建信息窗口
    marker.infoWindow = new AMap.InfoWindow({
      content: `<style>
        .custom-info-window {
          background-color: #fff;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          padding: 10px;
          font-size: 14px;
          color: #333;
        }
      </style>
      <div class="custom-info-window">
        <div class="custom-info-title" style="font-size: 14px;">${tempItem.name}</div>
      </div>`,
      offset: new AMap.Pixel(0, -45),
      closeWhenClickMap: true,
      isCustom: true,
    });

    // 标记选中状态
    selectedResult.value = tempItem;

    // 显示信息窗口
    marker.infoWindow.open(map, position);
    window.currentInfoWindow = marker.infoWindow;

    // 移动地图到目标位置
    map.setCenter(position, true);
    map.setZoom(17, true);
  });
};

const handleCloseSearch = () => {
  // 获取当前图片路径
  const currentImgSrc = showCloseIcon.value
    ? '../public/关闭.png'
    : '../public/dire.png';

  if (currentImgSrc === '../public/关闭.png') {
    // 清除地图标记
    searchMarkers.value.forEach((marker) => {
      map.remove(marker);
    });
    searchMarkers.value = [];

    // 清除搜索框内容及相关状态
    searchQuery.value = '';
    searchSuggestions.value = [];
    allResults.value = [];
    showAllResults.value = false;
    showCloseIcon.value = false;
    selectedResult.value = null;
  } else {
    // 显示路线规划器
    isTransitioning.value = true;
    showSearch.value = false;
    isSearchOpen.value = false;

    // 延迟切换状态以触发过渡动画
    setTimeout(() => {
      showRoutePlanner.value = true;
      isTransitioning.value = false;
    }, 300);
  }
};

// 修改返回搜索的方法
const handleBackToSearch = () => {
  // 开始过渡动画
  isTransitioning.value = true;
  
  // 清除地图上的路线
  if (currentDriving.value) {
    currentDriving.value.clear();
    currentDriving.value = null;
  }

  // 隐藏结果面板
  const panel = document.getElementById('panel');
  if (panel) {
    panel.style.display = 'none';
  }

  // 清空输入框内容
  startPoint.value = '';
  endPoint.value = '';
  waypoint.value = '';
  startaddress.value = '';
  endaddress.value = '';
  waypointaddress.value = '';
  
  // 隐藏途径点输入框
  showWaypoint.value = false;
  
  // 隐藏清除路线按钮
  showClearBtn.value = false;
  
  // 清空路线点数组
  points.value = [];
  
  // 重置活跃输入状态
  activeInput.value = '';
  
  // 清空路线搜索建议
  routesearchSuggestions.value = [];
  routesearchQuery.value = '';
  
  // 隐藏"我的位置"提示
  showMyLocation.value = false;
  showMyLocation1.value = false;
  showRouteHistory.value = false;

  // 延迟切换显示状态以完成过渡动画
  setTimeout(() => {
    showRoutePlanner.value = false;
    showSearch.value = true;
    isTransitioning.value = false;
  }, 300); // 与CSS过渡动画时长保持一致
};
// 添加新的途径点（修正版）
const addWaypoint = () => {
  isshowWaypoints.value = true;
  showWaypoint.value = true;
  hasWaypoint.value = true;
  document.querySelector('.route-planner .top').style.height = '260px';
  document.querySelector('.route-planner .input-box .inputs').style.top =
    '-22px';
  document.querySelector('.route-planner .close').style.top = '-210px';
};

// 删除指定索引的途径点（修正版）
const removeWaypoint = () => {
  isshowWaypoints.value = false;
  hasWaypoint.value = false;

  showWaypoint.value = false;
  waypoint.value = ''; // 清空途径点值
  waypointaddress.value = ''; // 清空途径点地址
  document.querySelector('.route-planner .top').style.height = '215px';
  document.querySelector('.route-planner .input-box .inputs').style.top = '0px';
  document.querySelector('.route-planner .close').style.top = '-165px';
};

// 选择交通方式
const selectMode = (newMode) => {
  // 切换模式时清除现有路线
  if (currentRoute.value) {
    currentRoute.value.clear();
    currentRoute.value = null;
  }
  mode.value = newMode;
  
  // 根据模式更新按钮文本
  const searchBtn = document.querySelector('.search-btn');
  if (searchBtn) {
    switch(newMode) {
      case 'car':
        searchBtn.textContent = '开车去';
        break;
      case 'bus':
        searchBtn.textContent = '公交去';
        break;
      case 'walk':
        searchBtn.textContent = '步行去';
        break;
    }
  }
};


// 切换起点终点
const switchInput = () => {
  const temp = startPoint.value;
  startPoint.value = endPoint.value;
  endPoint.value = temp;
};

// 新增：删除路线历史记录
const handleDeleteRouteHistory = async (id) => {
  try {
    // 1. 调用删除接口（假设已有deleterouteHistoryApi方法）
    await deleterouteHistoryApi(id);
    
    // 2. 从本地列表中移除该记录（更新UI）
    const index = routehistoryList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      routehistoryList.value.splice(index, 1);
    }
    
    console.log('路线历史记录删除成功');
  } catch (error) {
    console.error('删除路线历史记录失败:', error);
  }
};
// 点击路线历史记录，自动填充并规划路线
const handleRouteHistoryClick = (item) => {
  // 1. 填充起点、终点和途经点
  startPoint.value = item.points.start_point;
  endPoint.value = item.points.end_point;
  
  // 若有途经点，显示途经点输入框并填充
  if (item.points.pass_point && item.points.pass_point !== '') {
    showWaypoint.value = true;
    waypoint.value = item.points.pass_point;
    // 调整路线规划器高度（适配途经点）
    document.querySelector('.route-planner .top').style.height = '260px';
    document.querySelector('.route-planner .input-box .inputs').style.top = '-22px';
    document.querySelector('.route-planner .close').style.top = '-210px';
  } else {
    // 无途经点时隐藏输入框
    showWaypoint.value = false;
    waypoint.value = '';
  }

  // 2. 自动触发路线规划（复用已有的handleRouteSearch方法）
  handleRouteSearch();
};
// 处理路线图标/关闭图标的点击事件
const handleDirectionClick = () => {
  // 若当前显示的是路线图标（不是关闭图标）
  if (!showCloseIcon.value) {
    // 显示路线规划器（原有逻辑）
    isTransitioning.value = true;
    showSearch.value = false;
    isSearchOpen.value = false;
    setTimeout(() => {
      showRoutePlanner.value = true;
      isTransitioning.value = false;
    }, 300);
    // 同时显示路线搜索记录
    showRouteHistory.value = true;
  } else {
    // 原有关闭逻辑（保持不变）
    handleCloseSearch();
  }
};
const handleDireImageClick = (item) => {
  // 隐藏搜索结果区域
  showAllResults.value = false;
  
  // 切换到路线规划界面
  showSearch.value = false;
  isTransitioning.value = true;
  showRouteHistory.value = true;
  // 延迟切换状态以确保过渡动画生效
  setTimeout(() => {
    showRoutePlanner.value = true;
    isTransitioning.value = false;
    
    // 填充起点为"我的位置"，终点为搜索结果
    // startPoint.value = "我的位置";
    endPoint.value = item.name;
    // startaddress.value = myLocation.value;
    endaddress.value = item.address || '';
    
    // 自动触发路线搜索
    // handleRouteSearch();
  }, 300);
};


// 获取当前时间
const data = new Date();
const year = data.getFullYear();
const month = data.getMonth() + 1;
const day = data.getDate();
const hours = data.getHours();
const minutes = data.getMinutes();
const date = ref(`${year}/${month}/${day} `);
const time = ref(`${hours}:${minutes}`);
watch(showWaypoint, (newVal) => {
  const panel = document.getElementById('panel');
  if (panel) {
    if (newVal) {
      panel.classList.add('waypoint-active');
    } else {
      panel.classList.remove('waypoint-active');
    }
  }
});
onUnmounted(() => {
  if (locationMarker) {
    map.remove(locationMarker);
  }
  map?.destroy();
});
</script>

<style scoped>
/* 历史记录 */
.routehistory{
  position: fixed;
  top: 236px;
  left: 15px;
  background-color: white;
  width: 360px;
  border-radius: 0 0 4px 4px;
  box-shadow:  0 2px 2px rgba(0, 0, 0, 0.3);
  transition: top 0.3s ease;
}
.routehistory .title{
  display: flex;
  height: 47px;
  align-items: center;
  border-bottom: 1px solid #e5e5e5;
}
.routehistory .title img{
  margin-right: 15px;
  margin-left: 15px;
}
.routehistory .title .text{
  height: 100%;
  width: 100%;
  line-height: 41px;
}
.routehistory .history-list{
  display: flex;
  flex-direction: column;
}
.routehistory .history-list .list-item{
  display: flex;
  padding: 5px 5px 5px 0px;
  justify-content: space-between;
}
.routehistory .history-list .list-item:hover{
  background-color: #f0eeee;
}
.routehistory .history-list .list-item .left{
  display: flex;
  margin-left: 15px;
  gap:3px;
  cursor: pointer;
    /* 核心样式：限制单行显示并省略 */
  max-width: 280px; /* 根据容器宽度调整，预留关闭按钮空间 */
  overflow: hidden; /* 隐藏超出部分 */
  white-space: nowrap; /* 禁止换行 */
  text-overflow: ellipsis; /* 超出部分显示... */
}
.routehistory .history-list .list-item .left .search-icon{
margin-right: 12px;
}
.routehistory .history-list .list-item .close{
  margin-right: 10px;
  cursor: pointer;
}
/* 路线 */
#panel {
  background-color: #fff;
  width: 360px;
  position: fixed;
  top: 235px;
  left: 15px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
}
#panel.waypoint-active {
  transform: translateY(40px);
}
/* 路径规划器搜索提示区域标题 */
.routesuggestions {
  position: fixed;
  top: 235px;
  left: 15px;
  height: 330px;
  width: 360px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
  background-color: white;
  border-radius: 0 0 4px 4px;
  color: #404040;
  font-size: 13px;
}
.routesuggestions .title {
  padding: 8px;
  display: flex;
  height: 32px;
}
.routesuggestions .title:hover {
  background-color: #f0eeee;
}
.routesuggestions .title img {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.routesuggestions-item {
  padding: 8px;
  display: flex;
  height: 32px;
}
.routesuggestions-item:hover {
  background-color: #f0eeee;
}
.routesuggestions-item img {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.my-location {
  background-color: white;
  padding: 12px;
  position: fixed;
  top: 236px;
  left: 15px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  width: 360px;
  cursor: pointer;
  display: flex;
  align-items: center;
  z-index: 10000;
}
.my-location img {
  margin-right: 10px;
}
.my-location .text {
  color: #11a9d8;
  font-size: 14px;
}
.my-location1 {
  background-color: white;
  padding: 12px;
  position: fixed;
  top: 280px;
  left: 15px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  width: 360px;
  cursor: pointer;
  display: flex;
  align-items: center;
  z-index: 10000;
}
.my-location1 img {
  margin-right: 10px;
}
.my-location1 .text {
  color: #11a9d8;
  font-size: 14px;
}
.route-planner .input-box .input-item input:focus {
  color: #fff; /* 聚焦时字体变为白色 */
}

.route-planner {
  position: fixed;
  top: 15px;
  left: 15px;
  z-index: 62000;
  background-color: #3d93fd;
  border-radius: 4px 4px 0 0; /* 增大圆角更柔和 */
  /* box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);  */
  width: 360px; /* 适当缩小宽度，更紧凑 */
  display: flex;
  flex-direction: column;
  color: #fff;
  overflow: hidden; /* 隐藏溢出内容，避免圆角失效 */
  /* 新增动画相关样式 */
  max-height: 0; /* 初始高度为0 */
  opacity: 0;
  transform: scaleY(0.8); /* 初始Y轴缩放 */
  transform-origin: top center; /* 从顶部中心点开始缩放 */
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: none;
}
/* 进入动画（下拉显示） */
.route-planner.route-enter {
  max-height: 300px; /* 足够容纳内容的高度 */
  opacity: 1;
  transform: scaleY(1); /* 完全显示 */
  pointer-events: auto;
}

/* 退出动画（上拉隐藏） */
.route-planner.route-leave {
  max-height: 0;
  opacity: 0;
  transform: scaleY(0.8);
}

.route-planner .top {
  padding: 16px;
  display: flex;
  flex-direction: column;
  position: relative; /* 作为switch-icon的定位容器 */
  min-height: 215px;
  transition: height 0.3s ease; /* 添加变化时将在0.3秒内平滑过渡 */
  overflow: hidden; /* 防止内容突然跳动 */
}

.route-planner .top .top-icon {
  display: flex;
  align-items: center;
  justify-content: space-around; /* 分散排列，更均衡 */
  gap: 30px;
}

.route-planner .top .top-icon div {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0.5; /* 初始透明度 */
}

.route-planner .top .top-icon div.active {
  opacity: 1;
}

.route-planner .top .top-icon img {
  width: 28px;
  height: 28px; /* 适当增大图标 */
}

.route-planner .input-box {
  display: flex;
  gap: 8px;
  position: relative;
  top: -25px;
  left: -8px;
}

.route-planner .input-box .switch-icon {
  position: absolute;
  top: 30px;
  left: -25px;
}

.route-planner .input-box .switch-icon img {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.route-planner .input-box .inputs {
  display: flex;
  flex-direction: column;
  gap: 8px;
  position: absolute;
  top: 0;
  left: 5px;
  transition: top 0.3s ease;
}

.route-planner .input-box .input-item {
  display: flex;
  align-items: center;
  background-color: #3587eb;
  padding: 8px 12px; /* 优化内边距 */
  width: 270px;
  position: relative;
}

.route-planner .input-box .input-item .label {
  width: 20px;
  text-align: center;
  color: #acd7ff; /* 修复文字颜色，确保可见 */
  font-size: 14px;
  margin-right: 5px;
  padding: 2px;
}

.route-planner .input-box .input-item input {
  flex: 1;
  background-color: transparent;
  border: none;
  outline: none;
  color: #fff;
  font-size: 14px; /* 增大输入文字 */
  padding-top: 0px;
}
.route-planner .input-box .input-item input::placeholder {
  color: #acd7ff; /* 修复输入框提示文字颜色 */
}
/* 输入框聚焦状态 */
.route-planner .input-box .inputs .input-item input:focus {
  color: #fff; /* 聚焦时保持文本颜色 */
  border-color: #4d90fe; /* 可选：添加聚焦边框效果 */
  outline: none;
}

/* 输入框禁用状态（如果有） */
.route-planner .input-box .inputs .input-item input:disabled {
  color: #999; /* 禁用时文本颜色 */
  background-color: #f5f5f5;
}

/* 终点输入框容器 - 启用flex布局容纳输入框和图标 */
.route-planner .input-box .input-item.end-point {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 8px; /* 输入框和图标之间的间距 */
}

/* 加号图标样式 */
.route-planner .input-box .input-item.end-point .icon2 {
  width: 23px;
  height: 23px;
  cursor: pointer;
  /* 去除绝对定位，使用flex布局自然排列 */
  position: relative;
  left: 45px;
}

.route-planner .search-btn {
  width: 92px;
  height: 32px;
  background-color: #559ffb;
  border: none;
  color: #fff;
  padding: 0 25px 0 25px;
  border-radius: 4px;
  cursor: pointer;
  position: absolute;
  right: 45px; /* 距离右侧内边距 */
  bottom: 16px; /* 距离底部内边距 */
  top: auto; /* 清除原有 top 定位 */
  left: auto; /* 清除原有 left 定位 */
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}

.route-planner .search-btn:hover {
  opacity: 0.7;
}
.route-planner .clear-btn {
  width: 104px;
  height: 32px;
  background-color: #559ffb;
  border: none;
  color: #fff;
  padding: 0 25px 0 25px;
  border-radius: 4px;
  cursor: pointer;
  position: absolute;
  right: 210px; /* 距离右侧内边距 */
  bottom: 16px; /* 距离底部内边距 */
  top: auto; /* 清除原有 top 定位 */
  left: auto; /* 清除原有 left 定位 */
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}

.route-planner .clear-btn:hover {
  opacity: 0.7;
}

.route-planner .close {
  position: relative;
  top: -165px;
  right: -155px;
  cursor: pointer;
  transition: top 0.3s ease;
}

.route-planner .close img {
  width: 20px;
  height: 20px;
}
.waypoint-item img {
  position: relative;
  top: 0px;
  left: 45px;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
/* 修改dire-image样式，使其靠右对齐 */
.dire-image {
  width: 40px;
  height: 40px;
  /* 关键调整：使用绝对定位靠右对齐 */
  position: absolute;
  right: 15px; /* 与容器右侧保持15px距离，和文字缩进一致 */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 精确垂直居中 */
}

/* 为result-name添加相对定位，作为图片的定位容器 */
.result-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 3px;
  position: relative; /* 让图片的绝对定位基于此元素 */
  padding-right: 30px; /* 预留图片位置，避免文字被图片遮挡 */
}

/* 确保result-item有足够的内边距容纳右侧图片 */
.result-item {
  display: flex;
  padding: 12px 15px; /* 右侧15px内边距，与图片右间距呼应 */
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f0f0f0;
  position: relative; /* 确保子元素绝对定位有效 */
}

.result-item:last-child {
  border-bottom: none;
}
/* 搜索结果显示样式 */
.search-result {
  position: fixed;
  top: 60px; /* 与搜索框对齐 */
  left: 15px;
  width: 360px;
  padding: 10px;
  background-color: white;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
  z-index: 6200; /* 确保在地图上方 */
}

.result-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.result-address {
  font-size: 14px;
  color: #666;
  max-width: 280px;
}
/* 搜索提示区域标题 */
.suggestions {
  position: fixed;
  top: 60px;
  left: 15px;
  height: 353px;
  width: 360px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
  background-color: white;
  border-radius: 0 0 4px 4px;
  color: #404040;
  font-size: 13px;
}
.suggestions .title {
  padding: 8px;
  display: flex;
  height: 32px;
}
.suggestions .title:hover {
  background-color: #f0eeee;
}
.suggestions .title img {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.suggestion-item {
  padding: 8px;
  display: flex;
  height: 32px;
}
.suggestion-item:hover {
  background-color: #f0eeee;
}
.suggestion-item img {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.search-item {
  height: 400px;
  width: 360px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
  background-color: white;
  border-radius: 0 0 4px 4px;
  position: fixed;
  top: 60px;
  left: 15px;
  display: flex;
  flex-direction: column;

  transform: translateY(-10px); /* 初始向上偏移 */
  opacity: 0; /* 初始透明 */
  pointer-events: none; /* 初始不可点击 */
  transition: all 0.3s ease-out; /* 过渡动画 */
}
/* 搜索项显示动画 */
.search-item.search-enter {
  transform: translateY(0); /* 回到正常位置 */
  opacity: 1; /* 完全显示 */
  pointer-events: auto; /* 可点击 */
}

/* 搜索项隐藏动画 */
.search-item.search-leave {
  transform: translateY(-10px); /* 向上偏移 */
  opacity: 0; /* 完全透明 */
  pointer-events: none; /* 不可点击 */
}

.search-item .top {
  height: 100px;
  display: flex;
  padding: 0px 14px 0 14px;
  border-bottom: 1px dashed #dbdee2;
  margin: 0px;
}
.search-item .top-item {
  height: 100%;
  width: 25%;
  text-align: center;
  cursor: pointer;
  padding-top: 15px;
}
.search-item .top-item:hover {
  background-color: #f8f8f8;
}
.search-item .top-item:hover .text {
  color: #4d91eb !important;
}
.search-item .top-item .text {
  padding-top: 5px;
}
.search-item .bottom {
  display: flex;
  flex-direction: column;
  margin-top: 5px;
  /* 新增以下样式 */
  height: calc(100% - 100px); /* 减去顶部区域高度，剩余空间用于历史记录 */
  overflow-y: auto; /* 超出时显示垂直滚动条 */
  overflow-x: hidden; /* 隐藏水平滚动条（如需） */
}
.search-item .bottom-item {
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  cursor: pointer;
}
.search-item .bottom-item:hover {
  background-color: #f8f8f8;
}
.search-item .bottom-item .left {
  display: flex;
}
.search-item .bottom-item .close {
  display: none;
  height: 100%;
  padding-top: 6px;
}
.search-item .bottom-item .icon {
  height: 100%;
  padding-top: 6px;
  margin-right: 10px;
}
.search-item .bottom-item:hover .close {
  display: block;
}
.search-item .bottom-item .text {
  height: 100%;
  line-height: 32px;
}
#container {
  width: 100%;
  height: 100vh;
}
.search {
  z-index: 6201;
  left: 15px;
  top: 15px;
  position: absolute;
}
.search-box {
  position: relative;
  z-index: 2201;
  width: 360px;
  height: 45px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
.search-box img {
  display: block;
  position: absolute;
  top: 6px;
  left: 8px;
  width: 34px;
  height: 34px;
  z-index: 99999;
  cursor: pointer;
}
.input-box {
  position: absolute;
  left: 50px;
  top: 0;
  width: 265px;
  height: 45px;
  box-sizing: border-box;
  z-index: 2202;
  border-radius: 2px;
}
#searchipt {
  position: absolute;
  top: 12.5px;
  left: 0;
  z-index: 2200;
  border: none;
  width: 219px;
  padding: 0;
  letter-spacing: 0.5px;
  font-size: 14px;
  text-indent: 2px;
  height: 20px;
  line-height: 20px;
  box-sizing: border-box;
  outline-color: initial;
  outline-style: initial;
  outline-width: 0px;
}
#searchipt::placeholder {
  color: #dbdbdb;
}
.search-btn {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 9308;
  box-sizing: border-box;
  width: 45px;
  height: 45px;
}

.iconfont {
  position: absolute;
  top: 10px;
  right: 8px;
  font-size: 25px;
  color: #7c8196;
  padding: 0 5px;
  cursor: pointer;
}
.iconfont:hover {
  color: #11a9d8;
}
.direction {
  width: 45px;
  height: 45px;
  position: absolute;
  right: 0;
  top: 0;
  text-align: center;
  background-color: #f8f8f8;
  border-radius: 0 3px 3px 0;
}
.direction img {
  position: absolute;
  top: 9px;
  right: 9px;
  width: 28px;
  height: 28px;
  padding: 5px;
  cursor: pointer;
}
.direction img:hover {
  opacity: 0.8;
}
.citybox {
  position: absolute;
  top: 15px;
  left: 395px;
  z-index: 1100;
  background: #fff;
  border-bottom-left-radius: 3px;
  border-top-left-radius: 3px;
  color: #5f6477;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  height: 45px;
  display: flex;
  font-size: 14px;
  padding: 8px;
  gap: 30px;
}

.city {
  position: fixed;
  top: 15px;
  left: 395px;
  background-color: white;
  border-radius: 4px 0 0 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  height: 45px;
  display: flex;
  align-items: center;
  padding: 0 5px 0 10px;
  font-size: 14px;
  color: #5f6477;
  cursor: pointer;
}
.city:hover {
  color: #4d91eb;
}
.city:hover .iconfont {
  color: #4d91eb;
}
.city .iconfont {
  position: relative;
  top: 2px;
  right: 0px;
  font-size: 16px;
}
.weather {
  position: fixed;
  top: 15px;
  left: 462px;
  background-color: white;
  border-radius: 0 4px 4px 0;
  height: 45px;
  font-size: 14px;
  color: #5f6477;
  cursor: pointer;
  text-align: center;
  padding: 2px 10px 0 0;
  box-shadow: 2px 2px rgba(0, 0, 0, 0.15);
  transform: translateX(100%);
  opacity: 0;
  /* 动画过渡：同时控制位移和透明度  */
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}
.weather.slide-in {
  transform: translateX(0); /* 滑到可视区域 */
  opacity: 1; /* 完全显示 */
}
.weather.slide-out {
  transform: translateX(-100%); /* 滑出可视区域 */
  opacity: 0; /*完全透明 */
}
.loginbox {
  position: absolute;
  width: 50px;
  height: 50px;
  right: 15px;
  top: 15px;
  z-index: 115;
  cursor: pointer;
  border: 2px solid #fff;
  border-radius: 50%;
}
.loginbox img {
  width: 46px;
  height: 46px;
  border-radius: 50%;
}
.location {
  position: absolute;
  bottom: 87px;
  right: 40px;
  z-index: 1100;
  background-color: #fff;
  width: 30px;
  height: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  cursor: pointer;
}
.icon-location {
  font-size: 18px;
  color: #4d91eb;
  position: absolute;
  top: 7px;
  left: 1px;
}
.controlbar {
  position: absolute;
  top: 15px;
  right: 80px;
  height: 45px;
  background-color: #fff;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  border-radius: 3px;
  color: #565656;
  font-size: 13px;
  font-family: Arial, sans-serif;
  padding: 10px;
  display: flex;
  align-items: center;
}
.controlbar .item {
  float: left;
  height: 18px;
  padding: 0 12px;
  font-size: 12px;
  border-left: 1px #dbdee2 dashed;
  vertical-align: middle;
  cursor: pointer;
  overflow: visible;
  zoom: 1;
  color: #5f6477;
  z-index: 10000;
}
.controlbar .item:first-child {
  border-left: none;
}
.controlbar .item .icon {
  display: inline-block;
  width: 18px;
  height: 20px;
  margin-right: 5px;
  color: #5f6477;
  vertical-align: middle;
  position: relative;
  top: -10px;
  right: -10px;
}
.controlbar .item .icon i {
  font-size: 18px;
}
.controlbar .item:hover {
  /* color: #c4c1c1; */
  opacity: 0.6;
}
.controlbar .item:hover .icon i {
  color: #5f6477;
  opacity: 0.6;
}

/* 退出全屏按钮样式 */
.exit-fullscreen {
  /* 保留核心样式，优化过渡逻辑 */
  position: fixed;
  top: 20px;
  right: -120px; /* 初始位置在可视区域外 */
  z-index: 10000;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 8px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  opacity: 0; /* 初始透明 */
  pointer-events: none; /* 初始不可点击（避免占位） */
  /* 关键：对所有动态变化的属性添加过渡 */
  transition: right 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

/* 显示状态的样式（通过类控制） */
.exit-fullscreen.show {
  right: 20px; /* 目标位置 */
  opacity: 1; /* 不透明 */
  pointer-events: auto; /* 可点击 */
  transition-delay: 0.1s;
}

/* 路网div基础样式（固定定位在右侧） */
.roadnet {
  position: fixed;
  top: 15px; /* 调整到合适位置（在卫星按钮下方） */
  right: 400px;
  background: #fff;
  padding: 11px 15px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  /* 初始状态：隐藏在右侧（向右滑出状态） */
  transform: translateX(100%);
  opacity: 0;
  /* 动画过渡：同时控制位移和透明度 */
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

/* 向左滑出显示的动画（滑入） */
.roadnet.slide-in {
  transform: translateX(0); /* 滑到可视区域 */
  opacity: 1; /* 完全显示 */
}

/* 向右滑出隐藏的动画（滑出） */
.roadnet.slide-out {
  transform: translateX(100%); /* 滑出可视区域 */
  opacity: 0; /* 完全透明 */
}

/* 复选框样式优化（可选） */
.roadnet input {
  margin-right: 5px;
  vertical-align: middle;
}
.roadnet span {
  font-size: 14px;
  color: #5f6477;
}
/* 卫星按钮激活状态（蓝色） */
.controlbar .item.active {
  color: #11a9d8; /* 文字变蓝色 */
}
/* 激活状态下的图标也变蓝色 */
.controlbar .item.active .icon i {
  color: #11a9d8;
}
.traffic {
  width: 334px;
  height: 82px;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  position: fixed;
  top: 70px;
  right: 15px;
  transform: translateY(-100%);
  opacity: 0;
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}
.traffic.slide-down {
  transform: translateY(0);
  opacity: 1;
}
.traffic.slide-up {
  transform: translateY(-100%);
  opacity: 0;
}
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}
.colors {
  display: flex;
  align-items: center;
}
.color1 {
  width: 25px;
  height: 6px;
  background: #34b000;
  margin-right: 2px;
  margin-left: 5px;
}
.color2 {
  width: 25px;
  height: 6px;
  background: #fecb00;
  margin-right: 2px;
}
.color3 {
  width: 25px;
  height: 6px;
  background: #df0100;
  margin-right: 2px;
}
.color4 {
  width: 25px;
  height: 6px;
  background: #8e0e0b;
  margin-right: 5px;
}
.bottom {
  margin-top: 15px;
}
/* 所有搜索结果容器 */
.all-results {
  position: fixed;
  top: 60px;
  left: 15px;
  width: 360px;
  max-height: 400px; /* 限制高度，超出滚动 */
  overflow-y: auto;
  background-color: white;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  z-index: 9999;
  padding: 10px 0;
}

/* 结果标题 */
.results-title {
  padding: 0 15px 10px;
  font-size: 14px;
  color: #999;
  border-bottom: 1px solid #eee;
}

/* 单个结果项 */
.result-item {
  display: flex;
  padding: 12px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:hover {
  background-color: #f8f8f8;
}

/* 结果序号 */
.result-number {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #4d91eb;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  margin-right: 10px;
  flex-shrink: 0; /* 防止序号被压缩 */
}

/* 结果信息 */
.result-info {
  flex-grow: 1;
}

.result-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 3px;
}

.result-address {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
<style>
@keyframes fallIn {
  0% {
    transform: translateY(-100px);
    opacity: 0;
  }
  70% {
    transform: translateY(10px);
    opacity: 1;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

.marker-image.animate-fall {
  animation: fallIn 0.5s cubic-bezier(0.215, 0.61, 0.355, 1) forwards;
}
</style>
